/******************************************************************************
* echo_client.c                                                               *
*                                                                             *
* Description: This file contains the C source code for an echo client.  The  *
*              client connects to an arbitrary <host,port> and sends input    *
*              from stdin.                                                    *
*                                                                             *
* Authors: Athula Balachandran <abalacha@cs.cmu.edu>,                         *
*          Wolf Richter <wolf@cs.cmu.edu>                                     *
*                                                                             *
*******************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <fcntl.h>
#include <time.h>

#define ECHO_PORT 9999
#define BUF_SIZE 4096*4

enum{
    ERR, ACC
};

int main(int argc, char* argv[])
{
    if (argc != 4)
    {
        fprintf(stderr, "usage: %s <server-ip> <port>",argv[0]);
        return EXIT_FAILURE;
    }

    char buf[BUF_SIZE];
        
    int status, sock;
    struct addrinfo hints;
	memset(&hints, 0, sizeof(struct addrinfo));
    struct addrinfo *servinfo; //will point to the results
    hints.ai_family = AF_INET;  //IPv4
    hints.ai_socktype = SOCK_STREAM; //TCP stream sockets
    hints.ai_flags = AI_PASSIVE; //fill in my IP for me

    if ((status = getaddrinfo(argv[1], argv[2], &hints, &servinfo)) != 0) 
    {
        fprintf(stderr, "getaddrinfo error: %s \n", gai_strerror(status));
        return EXIT_FAILURE;
    }

    if((sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1)
    {
        fprintf(stderr, "Socket failed");
        return EXIT_FAILURE;
    }
    
    if (connect (sock, servinfo->ai_addr, servinfo->ai_addrlen) == -1)
    {
        fprintf(stderr, "Connect");
        return EXIT_FAILURE;
    }
        
    char msg[BUF_SIZE]; 
    int fd_in = open(argv[3], O_RDONLY);
    //fgets(msg, BUF_SIZE, stdin);
    if(fd_in < 0) {
		printf("Failed to open the file\n");
		return 0;
	}
    read(fd_in,msg,BUF_SIZE);
    
    int bytes_received;
    //int mark;

    fprintf(stdout, "------------------Sending----------------- \n%s", msg);
    send(sock, msg , strlen(msg), 0);
    while((bytes_received = recv(sock, buf, BUF_SIZE, 0)) >= 1)
    {
        buf[bytes_received] = '\0';
        fprintf(stdout, "-----------------------Received-------------------- \n%s", buf);
/*
        int len = strlen(buf);
        char llen[5];
        memset(llen, 0, sizeof(llen));
        sprintf(llen, "%d", len);
        char* p = strtok(buf, "\n");

        if(strcmp(p, "HTTP/1.1 200 OK\r") == 0){
            mark = ACC;
            char info[50];
            memset(info, 0, sizeof(info));
            strcpy(info, " \"GET / HTTP/1.1\" 200 ");

            strcat(info, llen);
            write_log_file("log.txt", FILE_MAX_SIZE, info, strlen(info), mark);
        }
        else{
            mark = ERR;
            char info[30];
            memset(info, 0, sizeof(info));
            strcpy(info, p);

            write_log_file("log.txt", FILE_MAX_SIZE, info, strlen(info), mark);
        }
        */
    }      
    memset(msg, 0, sizeof(msg));
    
    freeaddrinfo(servinfo);
    close(sock);    
    return EXIT_SUCCESS;
}

/*
获得当前时间字符串
@param buffer [out]: 时间字符串
@return 空
*/
void get_local_time(char* now, int mark)
{
    time_t rawtime;
    struct tm* info;
    time(&rawtime);
    /*
    sprintf(buffer, "%04d-%02d-%02d %02d:%02d:%02d",
    (timeinfo->tm_year+1900), timeinfo->tm_mon + 1, timeinfo->tm_mday,
    timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
    */
    info = localtime( &rawtime );

    if( mark == ERR ){
        strftime(now, 80, "[%a %b %d %H:%M:%S %Y] ", info);
    }
    else if( mark == ACC ){
        strftime(now, 80, "[%d/%b/%Y:%H:%M:%S +0800]", info);
    }
}

/*
获得文件大小
@param filename [in]: 文件名
@return 文件大小
*/
long get_file_size(char* filename)
{
   long length = 0;
   FILE *fp = NULL;
   fp = fopen(filename, "rb");
   if (fp != NULL){
      fseek(fp, 0, SEEK_END);
      length = ftell(fp);
   }

   if (fp != NULL){
      fclose(fp);
      fp = NULL;
   }
   return length;
}


/*
写入日志文件
@param filename [in]: 日志文件名
@param max_size [in]: 日志文件大小限制
@param buffer [in]: 日志内容
@param buf_size [in]: 日志内容大小
@return 空
*/
void write_log_file(char* filename, long max_size, char* buffer, unsigned buf_size, int mark)
{
    if(filename != NULL && buffer != NULL){
        long length = get_file_size(filename);
        if( length > max_size){
            unlink(filename);
        }

        FILE* fp;
        fp = fopen(filename, "at+");
        if( fp != NULL){
            if( mark == ERR ){
                char info[max_size];
                memset(info, 0, sizeof(info));

                char now[50];
                memset(now, 0, sizeof(now));
                get_local_time(now, mark);
                strcpy(info, now);

                char wrong[10];
                memset(wrong, 0, sizeof(wrong));
                strcpy(wrong, "[error] ");
                strcat(info, wrong);

                char loc[30];
                memset(loc, 0, sizeof(loc));
                strcpy(loc, "[client ");
                strcat(loc, "127.0.0.1");
                strcat(loc, "]\n");
                strcat(info, loc);

                strcat(info, buffer);
                fwrite(info, strlen(info), 1, fp);
            }
            else if( mark == ACC ){
                char info[max_size];
                memset(info, 0, sizeof(info));

                char loc[20];
                memset(loc, 0, sizeof(loc));
                strcpy(loc, "127.0.0.1");
                strcpy(info, loc);

                strcat(info, " - - ");

                char now[30];
                get_local_time(now, mark);
                strcat(info, now);

                strcat(info, buffer);
                strcat(info, "\n");

                fwrite(info, strlen(info), 1, fp);
            }
        }
    }
}